<script setup>
import { ref, reactive, watch, onMounted, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { eventApi as MainApi, eventById as MainById, flowById , optionApi} from '@T2/service/api.ts';
import { useCurrentWatchStore, useIuserInfoStore } from '@T2/store/users.ts';
import { getMenuParams } from '@T2/utils/params.ts';
import { canConnectNodesDFS, isJSON } from '@T2/utils/utils.ts';
import { useRoute } from 'vue-router';
import Flow from '@T2/views/Project/Manage/components/tree/flow.vue';
import AddEvent from './components/addEvent.vue';
import StepEvent from './components/stepEvent.vue';

const route = useRoute();
const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info, getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight([]);

onMounted(async () => {
  const { flows } = getMenuParams(route.path);
  const [ flow0 ] = flows || [];
  if (!flow0?.v) {
    ElMessage.error('未配置流程！');
    return;
  }
  const data = await getFlowDetail(flow0.v);
  if (!data.id) {
    return;
  }
  Filter.flow = data.id;
  currentFlow.value = data;
  console.log('data',data);
  data.fron_data.nodes.forEach(item => {
    if (item?.properties?.status) {
      typeStatus.value.push(item.properties.status)
    }
  });
  
  calcPath(data);
  getLastNodeIds(data);
});
const typeStatus = ref([])
const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
  flow: null,
  status:null,
  create_user:'',
  create_time__range:[]

});

watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    console.log('2');
    Filter.page = 1;
  }
});
const excludeds = ['uploadAttachment', 'uploadImage'];
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      create_time__range:Filter.create_time__range.join(',')
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
    
    MainTable.data.forEach(item => {
      if (isJSON(item.request_params)) {
        item._request_params = JSON.parse(item.request_params);
      } else {
        item._request_params = [];
      }
    });
  });
}
/* 当前流程 */
const currentFlow = ref(null);
const getFlowDetail = (id) => {
  return new Promise((resolve, reject) => {
    flowById({
      method: 'get',
      id
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  })
}
/* 计算是否有完整的流程路径 */
const isCompleteRf = ref(false);
const calcPath = (obj) => {
  const { nodes, edges } = obj?.fron_data || {};
  if (!nodes || !edges) {
    ElMessage.warning('存在不完整路径！');
    isCompleteRf.value = false;
    return;
  }
  const startId = nodes.find(i => i.type === 'first')?.id;
  const endIds = nodes.filter(i => i.type === 'end').map(j => j.id);
  if (!startId || !endIds.length || !edges) {
    ElMessage.warning('存在不完整路径！');
    isCompleteRf.value = false;
    return;
  }
  const flag = canConnectNodesDFS(startId, endIds, edges, 'sourceNodeId', 'targetNodeId');
  if (!flag) {
    ElMessage.warning('存在不完整路径！');
    isCompleteRf.value = false;
    return;
  }
  isCompleteRf.value = true;
}
/* 获取当前流程结束nodes */
const lastNodesRf = ref([]);
const getLastNodeIds = (obj) => {
  const { nodes, edges } = obj?.fron_data || {};
  lastNodesRf.value = nodes?.filter(i => i.type === 'end')?.map(i => i.properties.sql_id) || [];
}

/* 新增 */
const addShowRf = ref(false);
const handleMainAdd = () => {
  addShowRf.value = true;
}
const closeAddPopup = (refresh) => {
  addShowRf.value = false;
  if (refresh) {
    GetMainTable();
  }
}

/* 详情，流转 */
const stepRt = reactive({
  show: false,
  event: null,
  type: '详情',
});
const handleMainStep = (row, type = '详情') => {
  stepRt.show = true;
  stepRt.event = row;
  stepRt.type = type;
}
const closeStepPopup = (refresh) => {
  stepRt.show = false;
  stepRt.event = null;
  stepRt.type = '详情';
  if (refresh) {
    GetMainTable();
  }
}

/* 删除 */
const handleMainDelete = (row) => {
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `是否要删除${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

</script>

<template>
  <div class="view flex">
    <div class="container flex-column mainCard">
      <el-form label-width="120px" class="flex t_form" @submit.native.prevent>
        <el-form-item label="状态：">
          <el-select v-model="Filter.status" clearable>
            <el-option
              v-for="item in typeStatus"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
            v-model="Filter.create_time__range"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>
        <el-form-item label="创建人：">
          <el-input v-model="Filter.create_user" clearable></el-input>
        </el-form-item>
        <el-form-item label="模糊查询：">
          <el-input v-model="Filter.search" clearable></el-input>
        </el-form-item>
        <div class="flex r_btn" v-if="isCompleteRf">
          <el-button type="primary" @click="handleMainAdd()">新增</el-button>
        </div>
      </el-form>
      <el-table :data="MainTable.data" scrollbar-always-on>
        <el-table-column label="名称" prop="name" fixed="left" min-width="120px"></el-table-column>
        <template
          v-if="MainTable.data.length"
          v-for="item in MainTable.data[0]._request_params?.filter(i => !excludeds.includes(i.UDID))"
        >
          <el-table-column
            :label="item.label"
            min-width="200px"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row._request_params.find(i => i.label === item.label)?.value || '' }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="状态" prop="status" min-width="120px">
          <template #default="scope">
            <span style="color: #409eff;">{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="create_user_truename" min-width="120px"></el-table-column>
        <el-table-column label="创建时间" prop="create_time" width="160px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="220px">
          <template #default="scope">
            <template v-if="!lastNodesRf.includes(scope.row.node)">
              <el-button link type="primary" @click="handleMainStep(scope.row, '流转')">
                下一步
              </el-button>
            </template>
            <el-button link type="primary" @click="handleMainStep(scope.row)">
              详情
            </el-button>
            <el-button link type="danger" @click="handleMainDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <AddEvent
    v-if="addShowRf"
    :currentFlow="currentFlow"
    @closed="closeAddPopup"
  />
  
  <StepEvent
    v-if="stepRt.show"
    :flow="currentFlow"
    :event="stepRt.event"
    :type="stepRt.type"
    @closed="closeStepPopup"
  />
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.container {
  
}
</style>

